package com.my.demo.controller;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import com.my.annotation.Param;
import com.my.framework.web.annotation.Query;
import com.my.framework.web.mvc.controller.BaseController;
import com.my.threadpool.Event;
import com.my.threadpool.ThreadPool;
import com.my.utils.DateTime;

@Controller
@RequestMapping("/test")
public class TestController extends BaseController {

	@Autowired
	private RestTemplate restTemplate;
	
	@Query(name = "测试访问速度,每次请求都随机睡这0-5000ms;", path = "/speed")
	public String speed() throws InterruptedException {
		int[] index= {0,0,0,0,0,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,4,4,4,5,5,6};
		int[] sleep= {0,5,10,100,500,1000,5000};
		Random r = new Random();
		int i = r.nextInt(index.length);
		
		
		//每隔10分钟,所有请求都慢下来
		DateTime sp=DateTime.current();
		if(sp.getMinute()%10==0) {
			Thread.sleep(1000);
			return "2000";
		}
		
		
		Thread.sleep(sleep[index[i]]);
		return sleep[index[i]] + "";
	}

	@Query(name = "随机生成请求", path = "/createRequest")
	@Param("要访问的地址")
	@Param("访问次数,如果为负数就永不结束")
	@Param("并发数")
	public String createRequest(String url, Integer count,Integer thread) {
		String s=restTemplate.getForObject(url, String.class);
		log.debug("请求结果:{}({})  : {}",url,count,s);
		if(count==null) {
			return s;
		}
		new Thread() {
			public void run() {
				ThreadPool pool=new ThreadPool(thread,thread,0,0);
				int total=count;
				Random rd=new Random();
				while(true) {
					try {
						for( int j=0;j<thread ;j++) {
							pool.execute(new Event() {
								@Override
								public void execute() throws Exception {
									restTemplate.getForObject(url, String.class);
								}
							});
						}
						int i=rd.nextInt(100);
						Thread.sleep(100*i);
						if(total<0) {
							continue;
						}
						if(total==0) {
							break;
						}
						total--;
					}catch(Exception ex) {
						log.debug(ex.getMessage());
					}
				}
			}
		}.start();
		return s;
	}

}
